﻿#include <QtCore>
#include "chat_message_define.h"
#include "chat_personal_define.h"

namespace helper {
void ReplaceEmojiMsgToImage(QString& source);
}

namespace {
static QString kHtmlTemporate = R"(
                               <div class="subhistory-item">
                                 <div class="subhistory-info">
                                   <div class="subhistory-nick" data-id="%1">%2</div><p class="subhistory-time">%3</p>
                                 </div>
                                 <div class="subhistory-content">%4</div>
                                 <div class="subhistory-line"></div>
                               </div>)";
static QString kUrlToHtml     = "<a href=\"%1\">%1</a>";
static QString kImgToHtml     = "<img class=\"history-img\" src=\"%1\" data-small=\"%2\">";
static QString kMp4ToHtml     = R"(
                               <video class="history-video" controls>
                                 <source src="%1" data-thumb="%2" type="video/mp4">
                               </video>)";
static QString kFileToHtml    = R"(
                               <a class="history-file inline-block clearfix", href="%1", target="_blank">
                                 <span class="file-img inline-block left file-%2"></span>
                                 <div class="file-name left">
                                   <h4>%3</h4>
                                   <p class="history-file-size">%4MB</p>
                                 </div>
                               </a>)";
static QString kAddrToHtml    = R"(
                               <div class="history-location inline-block">
                                 <span class="message-location-icon left"></span>
                                 <div class="history-location-desc left">
                                  <h4>%1</h4>
                                  <p class="history-file-size">%2, %3</p>
                                 </div>
                               </div>)";
static QString kLinkToHtml    = R"(
                               <a class="history-link inline-block clearfix", href="%1", target="_blank">
                                 <img class="history-link-thumb inline-block left" src="%2"/>
                                 <div class="history-link-desc left">
                                   <h4>%3</h4>
                                   <p class="history-file-size">%4</p>
                                 </div>
                               </a>)";

//处理表情的相对路径
void handle_chat_emoji_html(QString& source) {
  helper::ReplaceEmojiMsgToImage(source);
  //处理表情的相对路径
  source.replace("src=\"emoji/", "src=\"../emoji/");
  source.replace("src=\"qq/", "src=\"../qq/");
}

//处理纯url为a标签包含的链接，不包含空格和中文
void handle_chat_url_html(QString& source) {
  if (!source.startsWith("http") || source.contains(' ')) {
    return;
  }
  if (!source.contains(QRegExp("[\\x4e00-\\x9fa5]+"))) {
    source = kUrlToHtml.arg(source);
  }
  // TODO 正则表达式
}
}  // namespace

namespace helper {

//收藏-聊天记录-聊天记录
QString FavoriteSubHistory2Html(const QList<QVariant>& msgList) {
  QString res;
  for (auto& item : msgList) {
    QString content;
    auto    dataItem = item.toMap();
    auto    type     = dataItem["@datatype"].toInt();
    if (type == FavType_Text) {
      content = dataItem["datadesc"].toString();
      handle_chat_emoji_html(content);
      handle_chat_url_html(content);
    } else if (type == FavType_Image) {
      content = u8"[图片]";
    } else if (type == FavType_Video) {
      content = u8"[视频]";
    } else if (type == FavType_File) {
      content = u8"[文件]";
    } else {
      content = u8"[其他类型]";
      qWarning() << u8"不支持的二级聊天数据, type:" << type;
    }

    auto userId = dataItem["dataitemsource"].toMap()["fromusr"].toString();
    if (userId.isEmpty()) {
      userId = dataItem["dataitemsource"].toMap()["realchatname"].toString();
    }

    auto userName = dataItem["sourcename"].toString();
    handle_chat_emoji_html(userName);
    auto time = dataItem["sourcetime"].toString();
    res += kHtmlTemporate.arg(userId, userName, time, content).append('\n');
  }
  return res;
}

//收藏-聊天记录
QString FavoriteHistory2Html(const QList<QVariant>& msgList) {
  QString res;
  for (const QVariant& data : msgList) {
    QString content;
    auto    dataItem = data.toMap();
    auto    id       = dataItem["@dataid"].toString();
    auto    type     = dataItem["@datatype"].toInt();
    if (type == FavType_Text) {
      content = dataItem["datadesc"].toString();
      handle_chat_emoji_html(content);
      handle_chat_url_html(content);
    } else if (type == FavType_Image) {
      QString bigImg   = "images/" + FAV_BIG_IMAGE(id);
      QString smallImg = "images/" + FAV_SMALL_IMAGE(id);
      content          = kImgToHtml.arg(bigImg, smallImg);
    } else if (type == FavType_Video) {
      QString mp4File  = "video/" + FAV_VIDEO_FILE(id);
      QString mp4Thumb = "video/" + FAV_VIDEO_THUMB(id);
      content          = kMp4ToHtml.arg(mp4File, mp4Thumb);
    } else if (type == FavType_Link) {
      static QString kLinkPrefix =
          QDir(TARGET_OUTPUT_PATH + QString("../favorite/")).absolutePath() + "/";
      auto title = dataItem["datatitle"].toString();
      auto desc  = dataItem["datadesc"].toString();
      auto link  = dataItem["dataitemsource"].toMap()["link"].toString();
      if (link.isEmpty()) {
        link = dataItem["stream_weburl"].toString();
      }
      auto thumb = kLinkPrefix + "link/" + FAV_LINK_THUMB(id);
      if (!QFile::exists(thumb)) {
        thumb = "../img/wechat/link.jpg";
      }
      content = kLinkToHtml.arg(link, thumb, title, desc);
    } else if (type == FavType_Location) {
      auto addr      = dataItem["locitem"].toMap();
      auto addrLabel = addr["label"].toString();
      auto addrName  = addr["poiname"].toString();
      auto addrLat   = addr["lat"].toString();
      auto addrLng   = addr["lng"].toString();
      if (!addrName.isEmpty()) {
        addrLabel.append(", " + addrName);
      }
      content = kAddrToHtml.arg(addrLabel, addrLat, addrLng);
    } else if (type == FavType_File) {
      QString fileFmt   = dataItem["datafmt"].toString();
      QString filePath  = "files/" + FAV_FILE_RESOURCE(id, fileFmt);
      QString fileTitle = dataItem["datatitle"].toString();
      double  fileSize  = dataItem["fullsize"].toLongLong() / 1024.0 / 1024.0;
      content = kFileToHtml.arg(filePath, fileFmt, fileTitle, QString::number(fileSize, 'g', 2));
    } else if (type == FavType_InnerChatHistory) {
      auto    title = dataItem["datatitle"].toString();
      auto    desc  = dataItem["datadesc"].toString();
      auto    link  = FAV_SUB_HISTORY_HTML(id);
      QString thumb = "../img/wechat/link.jpg";
      content       = kLinkToHtml.arg(link, thumb, title, desc);
    } else if (type == FavType_MiniProgram) {
      auto title = u8"[小程序] " + dataItem["datatitle"].toString();
      auto desc  = dataItem["datadesc"].toString();
      auto link  = dataItem["appbranditem"].toMap()["pagepath"].toString();
      auto thumb = "link/" + FAV_LINK_THUMB(id);
      content    = kLinkToHtml.arg(link, thumb, title, desc);
    } else {
      content = u8"[不支持的文件类型]";
      qWarning() << "type:" << type << " unsupport";
    }

    auto userId = dataItem["dataitemsource"].toMap()["fromusr"].toString();
    if (userId.endsWith("@chatroom")) {
      userId.append(" ").append(dataItem["dataitemsource"].toMap()["realchatname"].toString());
    }

    // TODO(备注加上)
    auto userName = dataItem["datasrcname"].toString();
    handle_chat_emoji_html(userName);
    auto time = dataItem["datasrctime"].toString();
    res += kHtmlTemporate.arg(userId, userName, time, content).append('\n');
  }
  return res;
}

}  // namespace helper
